/***************************************************************************
 *   Copyright (C) 2008 by Rysiek Krol,,,   *
 *   rysiek@Babylon2   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/


#include "keywordsdialog.h"
#include "property.h"
#include "picturelistwidgetitem.h"

#include "viewerconstants.h"

#include <zlib.h>
#include <rexifdata.h>

#include "utils.h"

#include <QDomDocument>
#include <QDomElement>
#include <QDir>
#include <QTextCodec>

#ifdef WINDOWS
#include <windows.h>
#endif

#include <QCheckBox>
#include <QInputDialog>

/**
 * Constructor
 * @param parent - parent object, PictureManager type
 * @param selectMode - determine, if dialog is in selection Mode
 * @param fl 
 */
KeywordsDialog::KeywordsDialog( QWidget* parent,  bool selectMode, Qt::WFlags fl)
        : QDialog( parent, fl ), Ui::KeywordsDialog(), manager(dynamic_cast<PictureManager*>(parent)), selectMode(selectMode)
{
    setupUi(this);

    QString *keywordString = new QString();

    // wypelnianie listy etykiet z wlasciwosci
    QSet<QString> *keywords = this->manager->getItsProperty()->getKeywords();
    QSetIterator<QString> *iterator = new QSetIterator<QString>(*keywords);
    while (iterator->hasNext())
    {
        QListWidgetItem *item = new QListWidgetItem(QIcon(":/keywordUncheked"), iterator->next(),this->keywordsSelector);
        this->keywordsSelector->addItem(item);
    }
    delete iterator;
    if (!this->selectMode)
    {
        //Zaznaczanie wybranych etykiet i uzupelnianie listy o etykiety w liscie
        QList<QListWidgetItem *> items = this->manager->getListWidget()->selectedItems();
        QListIterator<QListWidgetItem *> *listIterator = new QListIterator<QListWidgetItem*>(items);

        while (listIterator->hasNext())
        {
            PictureListWidgetItem *item = dynamic_cast<PictureListWidgetItem *>(listIterator->next());
            QSet<QString> *lista = item->getKeywords();
            iterator = new QSetIterator<QString>(*lista);
            while (iterator->hasNext())
            {
                QString keyword = iterator->next();
                QList<QListWidgetItem*> wynik = this->keywordsSelector->findItems(keyword, Qt::MatchExactly);
                if (wynik.count()>0)
                {
                    QListWidgetItem *item = wynik.first();
                    item->setIcon(QIcon(":/keywordChecked"));
                    item->setSelected(true);
                }
                else
                {
                    QListWidgetItem *item = new QListWidgetItem(keyword,this->keywordsSelector);
                    this->keywordsSelector->addItem(item);
                    item->setIcon(QIcon(":/keywordChecked"));
                    item->setSelected(true);
                }
                keywordString->append(keyword+",");
            }

        }

        keywordString->chop(1);
        this->keywordListBox->setText(*keywordString);
        delete keywordString;
        delete iterator;
        delete listIterator;
    }
    connect ( keywordsSelector, SIGNAL ( itemSelectionChanged() ), this, SLOT ( selectionChanged() ) );
    connect( keywordsSelector, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(itemClickedSlot(QListWidgetItem*)));
    QPalette palette = this->keywordsSelector->palette();
    palette.setBrush(QPalette::Highlight, palette.base());
    palette.setBrush(QPalette::HighlightedText, palette.text());
    this->keywordsSelector->setPalette(palette);

}

/**
 * Destructor
 */
KeywordsDialog::~KeywordsDialog()
{

}

/*$SPECIALIZATION$*/
void KeywordsDialog::addKeyword()
{

    bool ok;
    QString text = QInputDialog::getText(this, tr("New Keyword"), tr("Enter new keyword"), QLineEdit::Normal,"", &ok);
    if (ok)
    {
     QListWidgetItem *item = new QListWidgetItem(QIcon(":/keywordUncheked"), text,this->keywordsSelector);
        this->keywordsSelector->addItem(item);
    }

}

void KeywordsDialog::reject()
{
    QDialog::reject();
}

void KeywordsDialog::accept()
{
    QSet<QString> *keywords = this->manager->getItsProperty()->getKeywords();
    QSet<QString> *selected = new QSet<QString>();
    keywords->clear();
    for (int i=0; i<this->keywordsSelector->count();i++)
    {
        keywords->insert(this->keywordsSelector->item(i)->text());
        if (this->keywordsSelector->item(i)->isSelected()) selected->insert(this->keywordsSelector->item(i)->text());
    }

    keywords = new QSet<QString>();
    QList<QListWidgetItem *> items = this->manager->getListWidget()->selectedItems();
    QListIterator<QListWidgetItem *> *listIterator = new QListIterator<QListWidgetItem*>(items);

    while (listIterator->hasNext())
    {
        ((PictureListWidgetItem*)listIterator->next())->setKeywords(new  QSet<QString>(*selected));
    }
    delete selected;
    delete listIterator;
    if(!this->selectMode)this->buildCommentString();
    
    QDialog::accept();
}

void KeywordsDialog::keyPressEvent(QKeyEvent * event)
{
    switch (event->key())
    {
    case Qt::Key_Delete :
        QListWidgetItem *item = this->keywordsSelector->takeItem(this->keywordsSelector->currentRow());
        delete item;
    }
}

void KeywordsDialog::selectionChanged()
{
    QString keywordString;
    QList<QListWidgetItem *> items = this->keywordsSelector->selectedItems();
    QListIterator<QListWidgetItem *> *iterator = new QListIterator<QListWidgetItem*>(items);
    while (iterator->hasNext())
    {
        keywordString.append(iterator->next()->text()+",");
    }
    delete iterator;
    keywordString.chop(1);
    this->keywordListBox->setText(keywordString);
}



/**
* Buduje QString do zapisania w pliku z komentarzem i wywoluje metode zapisujaca
*/
void KeywordsDialog::buildCommentString()
{
    QDomDocument doc;
    QList<QListWidgetItem*> selectedList = this->manager->getListWidget()->selectedItems();

    for (int i=0; i<selectedList.size(); i++)
    {
        if (((PictureListWidgetItem*)selectedList.at(i))->getCommentString().isEmpty() )
        {
            doc = Utils::buildNewComment();
        }
        else
        {
            doc.setContent(((PictureListWidgetItem*)selectedList.at(i))->getCommentString());
        }
        QDomElement rootElement = doc.firstChildElement("Comment");
        QDomElement oldElement = rootElement.firstChildElement("Keywords");
        QDomElement newElement = doc.createElement("Keywords");
        QDomText t = doc.createTextNode(this->keywordListBox->text());
        newElement.appendChild(t);
        if(oldElement.isNull()){
            rootElement.appendChild(newElement);
        } else {
            rootElement.replaceChild(newElement, oldElement);
        }

        QString commentString = Utils::encodeCharacters(doc.toString());
        Utils::writeComment(commentString ,i, selectedList);
        this->done(1);
    }
}


void KeywordsDialog::itemClickedSlot(QListWidgetItem * item){
    if (item->isSelected()){
        item->setIcon(QIcon(":/keywordChecked"));

    } else {
        item->setIcon(QIcon(":/keywordUncheked"));
    }



}

/**
 *  Returns keyword string
 * @return QString
 */
QString KeywordsDialog::getKeywordString()
{
	return this->keywordListBox->text();
}





